import { apiRequest } from '../utils/api';
import { AuthResponse, LoginRequest, RegisterRequest } from '../types/auth';

// 登录服务
export const login = async (credentials: LoginRequest): Promise<AuthResponse> => {
  try {
    const responseData = await apiRequest<AuthResponse>('/auth/login', {
      method: 'POST',
      body: JSON.stringify(credentials),
    });
    
    // 保存token和用户信息
    storeToken(responseData.access_token, responseData.user);
    return responseData;
  } catch (error) {
    console.error('登录请求失败:', error);
    throw error;
  }
};

// 注册服务
export const register = async (userData: RegisterRequest): Promise<AuthResponse> => {
  try {
    const responseData = await apiRequest<AuthResponse>('/users/register', {
      method: 'POST',
      body: JSON.stringify(userData),
    });
    
    // 保存token和用户信息
    storeToken(responseData.access_token, responseData.user);
    return responseData;
  } catch (error) {
    console.error('注册请求失败:', error);
    alert('注册失败，请检查输入信息');
    throw error;
  }
};

// 登出服务
export const logout = (): void => {
  clearToken();
};

// 保存token和用户信息到localStorage
export const storeToken = (token: string, user?: any): void => {
  if (typeof window !== 'undefined') {
    localStorage.setItem('auth_token', token);
    if (user) {
      localStorage.setItem('user', JSON.stringify(user));
    }
  }
};

// 获取token
export const getToken = (): string | null => {
  if (typeof window !== 'undefined') {
    return localStorage.getItem('auth_token');
  }
  return null;
};

// 清除token
export const clearToken = (): void => {
  if (typeof window !== 'undefined') {
    localStorage.removeItem('auth_token');
    localStorage.removeItem('user');
  }
};

// 获取当前用户信息
export const getCurrentUser = (): any | null => {
  if (typeof window !== 'undefined') {
    const userStr = localStorage.getItem('user');
    if (userStr) {
      try {
        return JSON.parse(userStr);
      } catch (error) {
        console.error('解析用户信息失败:', error);
        return null;
      }
    }
  }
  return null;
};

// 检查是否已登录
export const isAuthenticated = (): boolean => {
  return !!getToken();
};
